package controllers

import (
	"bbf/models"
	beego "github.com/beego/beego/v2/server/web"
	"math"
)

type Bbf struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *Bbf) Add() {
	name := c.GetString("name")
	num, _ := c.GetInt("num")
	sj := c.GetString("sj")
	fzr := c.GetString("fzr")
	tel := c.GetString("tel")
	adtime := c.GetString("adtime")
	JsId, _ := c.GetInt("js_id")
	var bf = models.Ks{
		Name:   name,
		Num:    num,
		Sj:     sj,
		Fzr:    fzr,
		Tel:    tel,
		Adtime: adtime,
		JsId:   JsId,
	}
	err := models.DB.Create(&bf).Error

	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}

}
func (c *Bbf) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Ks{}, id).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *Bbf) List() {
	name := c.GetString("name")
	query := models.DB.Model(&models.Ks{})
	if name != "" {
		query.Where("name like ?", "%"+"%")
	}
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 4)
	up := page - 1
	if up < 1 {
		up = 1
	}
	var count int64
	query.Count(&count)
	sum := int(math.Ceil(float64(count) / float64(size)))
	offset := (page - 1) * size
	down := page + 1
	if down > sum {
		down = sum
	}
	var kk []models.Ks
	err := query.Preload("Js").Limit(size).Offset(offset).Find(&kk).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		pageData := make(map[string]interface{})
		pageData["sum"] = sum
		pageData["up"] = up
		pageData["down"] = down
		pageData["kk"] = kk
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "查询成功",
			Data: pageData,
		}
		c.ServeJSON()
	}
}
func (c *Bbf) Update() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "文件获取失败",
			Data: nil,
		}
		c.ServeJSON()
	}
	if header.Size > 2*1024*1024 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "图片大小不能超过2mb",
			Data: nil,
		}
		c.ServeJSON()
	}
	defer file.Close()
	path := "/static/img/" + header.Filename
	c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "上传成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
